package cn.talk.doodle.ability.base;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import cn.talk.doodle.ResourceTable;
import cn.talk.doodle.component.DoodleSeekBar;
import cn.talk.doodle.core.IDoodle;
import cn.talk.doodle.core.IDoodleColor;
import cn.talk.doodle.core.IDoodleItem;
import cn.talk.doodle.core.IDoodleItemListener;
import cn.talk.doodle.core.IDoodlePen;
import cn.talk.doodle.core.IDoodleSelectableItem;
import cn.talk.doodle.core.IDoodleShape;
import cn.talk.doodle.core.IDoodleTouchDetector;
import cn.talk.doodle.dialog.ColorPickerDialog;
import cn.talk.doodle.dialog.DialogController;
import cn.talk.doodle.dialog.Toast;
import cn.talk.doodle.imagepicker.ImageSelectorView;
import cn.talk.doodle.util.ImageUtils;
import cn.talk.doodle.util.PhotoEncode;
import cn.talk.doodle.util.StringUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.ColorConverter;
import ohos.agp.colors.ColorSpec;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.ColorMatrix;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.Window;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ColorSpace;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;
import ohos.utils.net.Uri;

import static cn.talk.doodle.ResourceTable.Id_doodle_container;

/**
 * 涂鸦界面，根据DoodleView的接口，提供页面交互
 * （这边代码和ui比较粗糙，主要目的是告诉大家DoodleView的接口具体能实现什么功能，实际需求中的ui和交互需另提别论）
 * Created by huangziwei(154330138@qq.com) on 2016/9/3.
 */
public class DoodleActivity extends Ability implements Component.ClickedListener {

    public static final String TAG = "Doodle";
    public final static int DEFAULT_MOSAIC_SIZE = 20; // 默认马赛克大小
    public final static int DEFAULT_COPY_SIZE = 20; // 默认仿制大小
    public final static int DEFAULT_TEXT_SIZE = 18; // 默认文字大小
    public final static int DEFAULT_BITMAP_SIZE = 80; // 默认贴图大小

    public static final int RESULT_ERROR = -111; // 出现错误
    public static final int RESULT_OK = -1;
    private DataAbilityHelper helper;
    private HiLogLabel logAble;
    private String rootPath;
    private Image result_pic;

    /**
     * 启动涂鸦界面
     *
     * @param activity  目标ability
     * @param params      涂鸦参数
     * @param requestCode startActivityForResult的请求码
     * @see DoodleParams*/

    public static void startActivityForResult(Ability activity, DoodleParams params, int requestCode) {
        Intent intent = new Intent();
      /*  Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(activity.getBundleName())
                .withAbilityName(DoodleActivity.class.getName())
                .build();*/
        Operation operation = new Intent.OperationBuilder()
                .withAction("ability.intent.QUERY_OPEN_DOODLE")
                .build();
        intent.setOperation(operation);
        intent.setParam(KEY_PARAMS, params);
        activity.startAbilityForResult(intent, requestCode);
    }

    /**
     * 启动涂鸦界面
     *
     * @param activity
     * @param imagePath   　图片路径
     * @param savePath    　保存路径
     * @param isDir       　保存路径是否为目录
     * @param requestCode 　startActivityForResult的请求码*/

    @Deprecated
    public static void startActivityForResult(Ability activity, String imagePath, String savePath, boolean isDir, int requestCode) {
        DoodleParams params = new DoodleParams();
        params.mImagePath = imagePath;
        params.mSavePath = savePath;
        params.mSavePathIsDir = isDir;
        startActivityForResult(activity, params, requestCode);
    }

    /**
     * {@link DoodleActivity#startActivityForResult(Ability, String, String, boolean, int)}
     */
    @Deprecated
    public static void startActivityForResult(Ability activity, String imagePath, int requestCode) {
        DoodleParams params = new DoodleParams();
        params.mImagePath = imagePath;
        startActivityForResult(activity, params, requestCode);
    }

    public static final String KEY_PARAMS = "key_doodle_params";
    public static final String KEY_IMAGE_PATH = "key_image_path";

    private String mImagePath;
    private Uri mImageUri;

    private StackLayout mFrameLayout;
    private IDoodle mDoodle;
    private DoodleView mDoodleView;

    private Text mPaintSizeView;

    private Component mBtnHidePanel, mSettingsPanel;
    private Component mSelectedEditContainer;
    private Text mItemScaleTextView;
    private Component mBtnColor, mColorContainer;
    //替换Slider为DoodleSeekBar，解决触屏事件冲突 每次都重置为0的bug
    private Slider mEditSizeSeekBar;
    private DoodleSeekBar mSeekBar;
    private Component mShapeContainer, mPenContainer, mSizeContainer;
    private Component mBtnUndo;
    private Component mMosaicMenu;
    private Component mEditBtn;
    private Component mRedoBtn;

    private AnimatorValue mViewShowAnimation, mViewHideAnimation; // view隐藏和显示时用到的渐变动画

    private DoodleParams mDoodleParams;

    // 触摸屏幕超过一定时间才判断为需要隐藏设置面板
    private Runnable mHideDelayRunnable;
    // 触摸屏幕超过一定时间才判断为需要显示设置面板
    private Runnable mShowDelayRunnable;

    private DoodleOnTouchGestureListener mTouchGestureListener;
    private Map<IDoodlePen, Float> mPenSizeMap = new HashMap<>(); //保存每个画笔对应的最新大小

    private int mMosaicLevel = -1;

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        outState.putSequenceableObject(KEY_PARAMS, mDoodleParams);
       // initDoodleData();
    }

    @Override
    public void onRestoreAbilityState(PacMap savedInstanceState) {
        super.onRestoreAbilityState(savedInstanceState);
        Optional<Sequenceable> optionalSequenceable = savedInstanceState.getSequenceable(KEY_PARAMS);
        mDoodleParams = (DoodleParams) optionalSequenceable.get();
       // initDoodleData();
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setUIContent(ResourceTable.Layout_doodle_layout);
        addActionRoute(Intent.ACTION_QUERY_WEATHER, DoodleActivity.class.getName());

        logAble = new HiLogLabel(HiLog.LOG_APP, 9, "DoodleActivity");
        helper = DataAbilityHelper.creator(getContext());
        rootPath = getFilesDir().getAbsolutePath() + File.separator + "doodleImages" +  File.separator;
        //initDoodleData();

        if (mDoodleParams == null) {
            mDoodleParams = getIntent().getSequenceableParam(KEY_PARAMS);
        }
        if (mDoodleParams == null) {
            System.out.println("TAG"+ "mDoodleParams is null!");
            this.terminateAbility();
            return;
        }

        mImagePath = mDoodleParams.mImagePath;
        mImageUri = Uri.parse(mDoodleParams.mImageUriStr) ;
        if (mImageUri == null) {
            System.out.println("TAG"+ "mImageUri is null!");
            this.terminateAbility();
            return;
        }

        System.out.println("TAG"+ mImagePath);
        if (mDoodleParams.mIsFullScreen) {
            getWindow().setLayoutFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN, WindowManager.LayoutConfig.MARK_FULL_SCREEN);
            getWindow().setStatusBarColor(Color.WHITE.getValue());

        }
        PixelMap bitmap = ImageUtils.createPixelMapFromUri(mImageUri, this, helper);
        if (bitmap == null) {
            HiLog.info(logAble, "bitmap is null!");
            this.terminateAbility();
            return;
        }


        mFrameLayout = (StackLayout) findComponentById(Id_doodle_container);


       /** Whether or not to optimize drawing, it is suggested to open, which can optimize the drawing speed and performance.
        Note: When item is selected for editing after opening, it will be drawn at the top level, and not at the corresponding level until editing is completed.
        是否优化绘制，建议开启，可优化绘制速度和性能.
        注意：开启后item被选中编辑时时会绘制在最上面一层，直到结束编辑后才绘制在相应层级*/

        mDoodle = mDoodleView = new DoodleViewWrapper(this, bitmap, mDoodleParams.mOptimizeDrawing, new IDoodleListener() {
            @Override
            public void onSaved(IDoodle doodle, PixelMap bitmap, Runnable callback) { // 保存图片为jpg格式
                File doodleFile = null;
                File file = null;
                //测试结果
            /*    if (bitmap != null){
                    result_pic.setPixelMap(bitmap);
                    return;
                }*/
                String savePath = mDoodleParams.mSavePath;
                boolean isDir = mDoodleParams.mSavePathIsDir;
                if (!StringUtils.isEmpty(savePath)) {
                    if (isDir) {
                        doodleFile = new File(savePath);
                        //　保存的路径
                        file = new File(doodleFile, System.currentTimeMillis() + ".jpg");
                    } else {
                        file = new File(savePath);
                    }
                }
                else {
                    File dcimFile = new File(rootPath, "DCIM");

                    doodleFile = new File(dcimFile, "Doodle");
                    if (!doodleFile.getParentFile().exists()){
                        doodleFile.mkdirs();
                    }
                    //　保存的路径
                    file = new File(doodleFile, System.currentTimeMillis() + ".jpg");
                }

                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file);
                    //图片保存成功
                    if (new PhotoEncode.Bulider()
                            .format("image/jpeg")
                            .quality(90)
                            .build()
                            .encodePhoto(outputStream, bitmap)){
                        Intent intent = new Intent();
                        intent.setParam(KEY_IMAGE_PATH, file.getAbsolutePath());
                        setResult(RESULT_OK, intent);

                    }else{
                        HiLog.info(logAble, "doodleActivity: 图片保存失败");
                        closeQuietly(outputStream);
                        callback.run();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    onError(DoodleView.ERROR_SAVE, e.getMessage());
                } finally {
                    closeQuietly(outputStream);
                    callback.run();
                    terminateAbility();
                }
            }

            public void closeQuietly(Closeable closeable) {
                if (closeable != null) {
                    try {
                        closeable.close();
                    } catch (RuntimeException var2) {
                        throw var2;
                    } catch (Exception var3) {
                    }
                }

            }

            public void onError(int i, String msg) {
                setResult(RESULT_ERROR, null);
                terminateAbility();
            }

            @Override
            public void onReady(IDoodle doodle) {
//                mEditSizeSeekBar.setMaxValue(Math.min(mDoodleView.getWidth(), mDoodleView.getHeight()));

                float size = mDoodleParams.mPaintUnitSize > 0 ? mDoodleParams.mPaintUnitSize * mDoodle.getUnitSize() : 0;
                if (size <= 0) {
                    size = mDoodleParams.mPaintPixelSize > 0 ? mDoodleParams.mPaintPixelSize : mDoodle.getSize();
                }
                // 设置初始值
                mDoodle.setSize(size);
                // 选择画笔
                mDoodle.setPen(DoodlePen.BRUSH);
                mDoodle.setShape(DoodleShape.HAND_WRITE);
                mDoodle.setColor(new DoodleColor(mDoodleParams.mPaintColor));
                if (mDoodleParams.mZoomerScale <= 0) {
                    findComponentById(ResourceTable.Id_btn_zoomer).setVisibility(Component.HIDE);
                }
                mDoodle.setZoomerScale(mDoodleParams.mZoomerScale);
                mTouchGestureListener.setSupportScaleItem(mDoodleParams.mSupportScaleItem);

                // 每个画笔的初始值
                mPenSizeMap.put(DoodlePen.BRUSH, mDoodle.getSize());
                mPenSizeMap.put(DoodlePen.MOSAIC, DEFAULT_MOSAIC_SIZE * mDoodle.getUnitSize());
                mPenSizeMap.put(DoodlePen.COPY, DEFAULT_COPY_SIZE * mDoodle.getUnitSize());
                mPenSizeMap.put(DoodlePen.ERASER, mDoodle.getSize());
                mPenSizeMap.put(DoodlePen.TEXT, DEFAULT_TEXT_SIZE * mDoodle.getUnitSize());
                mPenSizeMap.put(DoodlePen.BITMAP, DEFAULT_BITMAP_SIZE * mDoodle.getUnitSize());
            }
        });
        mDoodle.setSize(5f);
        mTouchGestureListener = new DoodleOnTouchGestureListener(mDoodleView, new DoodleOnTouchGestureListener.ISelectionListener() {
            // save states before being selected
            IDoodlePen mLastPen = null;
            IDoodleColor mLastColor = null;
            Float mSize = null;

            IDoodleItemListener mIDoodleItemListener = new IDoodleItemListener() {
                @Override
                public void onPropertyChanged(int property) {
                    if (mTouchGestureListener.getSelectedItem() == null) {
                        return;
                    }
                    if (property == IDoodleItemListener.PROPERTY_SCALE) {
                        mItemScaleTextView.setText(
                                (int) (mTouchGestureListener.getSelectedItem().getScale() * 100 + 0.5f) + "%");
                    }
                }
            };

            @Override
            public void onSelectedItem(IDoodle doodle, IDoodleSelectableItem selectableItem, boolean selected) {
                if (selected) {
                    if (mLastPen == null) {
                        mLastPen = mDoodle.getPen();
                    }
                    if (mLastColor == null) {
                        mLastColor = mDoodle.getColor();
                    }
                    if (mSize == null) {
                        mSize = mDoodle.getSize();
                    }
                    mDoodleView.setEditMode(true);
                    mDoodle.setPen(selectableItem.getPen());
                    mDoodle.setColor(selectableItem.getColor());
                    mDoodle.setSize(selectableItem.getSize());
                    mSeekBar.setProgress((int) selectableItem.getSize());
//                    mEditSizeSeekBar.setProgressValue((int) selectableItem.getSize());
                    mSelectedEditContainer.setVisibility(Component.VISIBLE);
                    mSizeContainer.setVisibility(Component.VISIBLE);
                    mItemScaleTextView.setText((int) (selectableItem.getScale() * 100 + 0.5f) + "%");
                    selectableItem.addItemListener(mIDoodleItemListener);
                } else {
                    selectableItem.removeItemListener(mIDoodleItemListener);

                    if (mTouchGestureListener.getSelectedItem() == null) { // nothing is selected. 当前没有选中任何一个item
                        if (mLastPen != null) {
                            mDoodle.setPen(mLastPen);
                            mLastPen = null;
                        }
                        if (mLastColor != null) {
                            mDoodle.setColor(mLastColor);
                            mLastColor = null;
                        }
                        if (mSize != null) {
                            mDoodle.setSize(mSize);
                            mSize = null;
                        }
                        mSelectedEditContainer.setVisibility(Component.HIDE);
                    }
                }
            }

            @Override
            public void onCreateSelectableItem(IDoodle doodle, float x, float y) {
                if (mDoodle.getPen() == DoodlePen.TEXT) {
                    createDoodleText(null, x, y);
                } else if (mDoodle.getPen() == DoodlePen.BITMAP) {
                    createDoodleBitmap(null, x, y);
                }
            }
        }) {
            @Override
            public void setSupportScaleItem(boolean supportScaleItem) {
                super.setSupportScaleItem(supportScaleItem);
                if (supportScaleItem) {
                    mItemScaleTextView.setVisibility(Component.VISIBLE);
                } else {
                    mItemScaleTextView.setVisibility(Component.HIDE);
                }
            }
        };

        IDoodleTouchDetector detector = new DoodleTouchDetector(getApplicationContext(), mTouchGestureListener);
        mDoodleView.setDefaultTouchDetector(detector);

        mDoodle.setIsDrawableOutside(mDoodleParams.mIsDrawableOutside);
        mFrameLayout.addComponent(mDoodleView, ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        mDoodle.setDoodleMinScale(mDoodleParams.mMinScale);
        mDoodle.setDoodleMaxScale(mDoodleParams.mMaxScale);

        initView();
    }

    @Override
    protected boolean onTouchEvent(TouchEvent event) {


        return super.onTouchEvent(event);
    }

    @Override
    public void onEventDispatch() {
        super.onEventDispatch();
    }

    private void initDoodleData() {
        // 涂鸦参数
        mDoodleParams.mIsFullScreen = true;
        // 图片路径
        mDoodleParams.mImagePath = "/storage/emulated/0/DCIM/Camera/IMG_20210527_145123.jpg";

        // 初始画笔大小
        mDoodleParams.mPaintUnitSize = DoodleView.DEFAULT_SIZE;
        // 画笔颜色
        mDoodleParams.mPaintColor = getColor(ResourceTable.Color_red);
        // 是否支持缩放item
        mDoodleParams.mSupportScaleItem = true;
        // 图片Uri
        mDoodleParams.mImageUriStr = "dataability:///media/external/images/media/473";
    }

    private boolean canChangeColor(IDoodlePen pen) {
        return pen != DoodlePen.ERASER
                && pen != DoodlePen.BITMAP
                && pen != DoodlePen.COPY
                && pen != DoodlePen.MOSAIC;
    }

    // 添加文字
    private void createDoodleText(final DoodleText doodleText, final float x, final float y) {
        if (isTerminating()) {
            return;
        }
        //todo 添加文字
       /* DialogController.showInputTextDialog(this, doodleText == null ? null : doodleText.getText(), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = (v.getTag() + "").trim();
                if (TextUtils.isEmpty(text)) {
                    return;
                }
                if (doodleText == null) {
                    IDoodleSelectableItem item = new DoodleText(mDoodle, text, mDoodle.getSize(), mDoodle.getColor().copy(), x, y);
                    mDoodle.addItem(item);
                    mTouchGestureListener.setSelectedItem(item);
                } else {
                    doodleText.setText(text);
                }
                mDoodle.refresh();
            }
        }, null);
        if (doodleText == null) {
            mSettingsPanel.removeCallbacks(mHideDelayRunnable);
        }*/
    }

    //todo 添加贴图
    private void createDoodleBitmap(final DoodleBitmap doodleBitmap, final float x, final float y) {
       /* DialogController.showSelectImageDialog(this, new ImageSelectorView.ImageSelectorListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onEnter(List<String> pathList) {
                Bitmap bitmap = ImageUtils.createBitmapFromPath(pathList.get(0), mDoodleView.getWidth() / 4, mDoodleView.getHeight() / 4);

                if (doodleBitmap == null) {
                    IDoodleSelectableItem item = new DoodleBitmap(mDoodle, bitmap, mDoodle.getSize(), x, y);
                    mDoodle.addItem(item);
                    mTouchGestureListener.setSelectedItem(item);
                } else {
                    doodleBitmap.setBitmap(bitmap);
                }
                mDoodle.refresh();
            }
        });*/
        //todo mImageUri先写死借用一下图片
        PixelMap bitmap = ImageUtils.createPixelMapFromUriAndSize(mImageUri, helper,mDoodleView.getWidth() / 4, mDoodleView.getHeight() / 4);

        if (doodleBitmap == null) {
            IDoodleSelectableItem item = new DoodleBitmap(mDoodle, bitmap, mDoodle.getSize(), x, y);
            mDoodle.addItem(item);
            mTouchGestureListener.setSelectedItem(item);
        } else {
            doodleBitmap.setBitmap(bitmap);
        }
        mDoodle.refresh();
    }

    //++++++++++++++++++以下为一些初始化操作和点击监听+++++++++++++++++++++++++++++++++++++++++

    //
    private void initView() {
        mBtnUndo = findComponentById(ResourceTable.Id_btn_undo);
        result_pic = (Image) findComponentById(ResourceTable.Id_result_pic);
        mBtnUndo.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                if (!(DoodleParams.getDialogInterceptor() != null
                        && DoodleParams.getDialogInterceptor().onShow(DoodleActivity.this, mDoodle, DoodleParams.DialogType.CLEAR_ALL))) {
                    //todo 撤回操作
                    DialogController.showEnterCancelDialog(DoodleActivity.this,
                            getString(ResourceTable.String_doodle_clear_screen), getString(ResourceTable.String_doodle_cant_undo_after_clearing),
                            new Component.ClickedListener() {
                                @Override
                                public void onClick(Component v) {
                                    mDoodle.clear();
                                }
                            }, null
                    );
                }
            }

        });
        mSelectedEditContainer = findComponentById(ResourceTable.Id_doodle_selectable_edit_container);
        mSelectedEditContainer.setVisibility(Component.HIDE);
        mItemScaleTextView = (Text) findComponentById(ResourceTable.Id_item_scale);
        mItemScaleTextView.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                if (mTouchGestureListener.getSelectedItem() != null) {
                    mTouchGestureListener.getSelectedItem().setScale(1);
                }
            }
        });

        mSettingsPanel = findComponentById(ResourceTable.Id_doodle_panel);

        mBtnHidePanel = findComponentById(ResourceTable.Id_doodle_btn_hide_panel);

        mPaintSizeView = (Text) findComponentById(ResourceTable.Id_paint_size_text);
        mShapeContainer = findComponentById(ResourceTable.Id_shape_container);
        mPenContainer = findComponentById(ResourceTable.Id_pen_container);
        mSizeContainer = findComponentById(ResourceTable.Id_size_container);
        mMosaicMenu = findComponentById(ResourceTable.Id_mosaic_menu);
        mEditBtn = findComponentById(ResourceTable.Id_doodle_selectable_edit);
        mRedoBtn = findComponentById(ResourceTable.Id_btn_redo);

        findComponentById(ResourceTable.Id_btn_pen_hand).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_pen_mosaic).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_pen_copy).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_pen_eraser).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_pen_text).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_pen_bitmap).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_btn_brush_edit).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_undo).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_zoomer).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_set_color_container).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_btn_hide_panel).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_btn_finish).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_btn_back).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_btn_rotate).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_selectable_edit).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_selectable_remove).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_selectable_top).setClickedListener(this);
        findComponentById(ResourceTable.Id_doodle_selectable_bottom).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_hand_write).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_arrow).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_line).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_holl_circle).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_holl_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_fill_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_fill_circle).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_holl_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_fill_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_mosaic_level1).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_mosaic_level2).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn_mosaic_level3).setClickedListener(this);

        mBtnColor = DoodleActivity.this.findComponentById(ResourceTable.Id_btn_set_color);
        mColorContainer = DoodleActivity.this.findComponentById(ResourceTable.Id_btn_set_color_container);
//        mEditSizeSeekBar = (Slider) findComponentById(ResourceTable.Id_doodle_seekbar_size);
//
//        mEditSizeSeekBar.setProgressValue(5);
        mSeekBar = (DoodleSeekBar) findComponentById(ResourceTable.Id_doodle_seekbar_size);
        mSeekBar.setValueChangedListener((slider, progress) -> {
            mDoodle.setSize(progress);
            if (mTouchGestureListener.getSelectedItem() != null) {
                mTouchGestureListener.getSelectedItem().setSize(progress);
            }
        });
        mSeekBar.setProgress(5);
        if (mTouchGestureListener.getSelectedItem() != null) {
            mTouchGestureListener.getSelectedItem().setSize(1);
        }
//        mEditSizeSeekBar.setTouchFocusable(true);
//        mEditSizeSeekBar.setClickable(true);
//        mEditSizeSeekBar.setFocusable(FOCUS_ENABLE);
//        mEditSizeSeekBar.setTouchEventListener(new Component.TouchEventListener() {
//            @Override
//            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
//                MmiPoint pointerPosition = touchEvent.getPointerPosition(0);
//                boolean isHor = true;
//                float mx = pointerPosition.getX();
//                float barWidth =  mEditSizeSeekBar.getWidth();
//                int progress = (int) (100 * mx / barWidth);
////                mEditSizeSeekBar.getValueChangedListener().onProgressUpdated(mEditSizeSeekBar,progress,true);
//                mEditSizeSeekBar.setProgressValue(progress);
//                mDoodle.setSize(progress);
//                if (mTouchGestureListener.getSelectedItem() != null) {
//                    mTouchGestureListener.getSelectedItem().setSize(progress);
//                }
//                mEditSizeSeekBar.invalidate();
//                return true;
//            }
//        });
//        mEditSizeSeekBar.setValueChangedListener(new Slider.ValueChangedListener() {
//            @Override
//            public void onProgressUpdated(Slider slider, int progress, boolean b) {
//
//                if ((int) mDoodle.getSize() == progress && progress<=0) {
//                    return;
//                }
//                mDoodle.setSize(progress);
//                mDoodle.setSize(10);
//                if (mTouchGestureListener.getSelectedItem() != null) {
//                    // mTouchGestureListener.getSelectedItem().setSize(progress);
//                    mTouchGestureListener.getSelectedItem().setSize(10);
//                }
//                if (b){
//                    mEditSizeSeekBar.setProgressValue(progress);
//                    mDoodle.setSize(progress);
//                    if (mTouchGestureListener.getSelectedItem() != null) {
//                        mTouchGestureListener.getSelectedItem().setSize(progress);
//                    }
//                }
//            }
//
//            @Override
//            public void onTouchStart(Slider slider) {
//                slider.requestFocus();
//            }
//
//            @Override
//            public void onTouchEnd(Slider slider) {
//            }
//        });


        mDoodleView.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent event) {
                MmiPoint pointerPosition = event.getPointerPosition(0);
                // 隐藏设置面板  todo 添加轨迹绘制
                mDoodleView.onTouchEvent(component, event);

                if (!mBtnHidePanel.isSelected()  // 设置面板没有被隐藏
                        && mDoodleParams.mChangePanelVisibilityDelay > 0) {
                    switch (event.getAction()) {
                        case TouchEvent.PRIMARY_POINT_DOWN:
                           /* mSettingsPanel.removeCallbacks(mHideDelayRunnable);
                            mSettingsPanel.removeCallbacks(mShowDelayRunnable);
                            */
                            //触摸屏幕超过一定时间才判断为需要隐藏设置面板
                           // mSettingsPanel.postDelayed(mHideDelayRunnable, mDoodleParams.mChangePanelVisibilityDelay);
                            mDoodleView.invalidate();
                            break;
                        case TouchEvent.POINT_MOVE:
                            mDoodleView.invalidate();
                            break;
                        case TouchEvent.CANCEL:
                        case TouchEvent.PRIMARY_POINT_UP:
                            mDoodleView.invalidate();
                            break;

                    }
                }
                return true;
            }
        } );

        // 长按标题栏显示原图
        findComponentById(ResourceTable.Id_doodle_txt_title).setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent event) {

                switch (event.getAction()) {
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        component.setPressState(true);
                        mDoodle.setShowOriginal(true);
                        break;
                    case TouchEvent.PRIMARY_POINT_UP:
                    case TouchEvent.CANCEL:
                        component.setPressState(false);
                        mDoodle.setShowOriginal(false);
                        break;
                }
                return true;
            }
        });

        mViewShowAnimation = new AnimatorValue();
        mViewShowAnimation.setCurveType(Animator.CurveType.LINEAR);
        mViewShowAnimation.setDuration(150);
        mViewHideAnimation = new AnimatorValue();
        mViewShowAnimation.setCurveType(Animator.CurveType.LINEAR);
        mViewHideAnimation.setDuration(150);
        mHideDelayRunnable = new Runnable() {
            public void run() {
                hideView(mSettingsPanel);
            }

        };
        mShowDelayRunnable = new Runnable() {
            public void run() {
                showView(mSettingsPanel);
            }
        };
    }

    private AnimatorProperty mRotateAnimator;

    @Override
    public void onClick(final Component v) {
        if (v.getId() == ResourceTable.Id_btn_pen_hand) {
            mDoodle.setPen(DoodlePen.BRUSH);
        } else if (v.getId() == ResourceTable.Id_btn_pen_mosaic) {
            mDoodle.setPen(DoodlePen.MOSAIC);
        } else if (v.getId() == ResourceTable.Id_btn_pen_copy) {
            mDoodle.setPen(DoodlePen.COPY);
        } else if (v.getId() == ResourceTable.Id_btn_pen_eraser) {
            mDoodle.setPen(DoodlePen.ERASER);
        } else if (v.getId() == ResourceTable.Id_btn_pen_text) {
            mDoodle.setPen(DoodlePen.TEXT);
        } else if (v.getId() == ResourceTable.Id_btn_pen_bitmap) {
            mDoodle.setPen(DoodlePen.BITMAP);
        } else if (v.getId() == ResourceTable.Id_doodle_btn_brush_edit) {
            mDoodleView.setEditMode(!mDoodleView.isEditMode());
        } else if (v.getId() == ResourceTable.Id_btn_undo) {
            mDoodle.undo();
        } else if (v.getId() == ResourceTable.Id_btn_zoomer) {
            mDoodleView.enableZoomer(!mDoodleView.isEnableZoomer());
        } else if (v.getId() == ResourceTable.Id_btn_set_color_container) {
            DoodleColor color = null;
            if (mDoodle.getColor() instanceof DoodleColor) {
                color = (DoodleColor) mDoodle.getColor();
            }
            if (color == null) {
                return;
            }
            if (!(DoodleParams.getDialogInterceptor() != null
                    && DoodleParams.getDialogInterceptor().onShow(DoodleActivity.this, mDoodle, DoodleParams.DialogType.COLOR_PICKER))) {

                //todo 选择颜色
                new ColorPickerDialog(DoodleActivity.this,
                        new ColorPickerDialog.OnColorChangedListener() {
                            @Override
                            public void colorChanged(Color color, int size) {
                                mDoodle.setColor(new DoodleColor(color.getValue()));
                                mDoodle.setSize(size);
                            }

                            @Override
                            public void colorChanged(PixelMapElement color, int size) {
                                PixelMap bitmap = color.getPixelMap();
                                mDoodle.setColor(new DoodleColor(bitmap));
                                mDoodle.setSize(size);
                            }
                        }).show(mDoodleView, mBtnColor.getBackgroundElement(), Math.min(mDoodleView.getWidth(), mDoodleView.getHeight()));
            }
        } else if (v.getId() == ResourceTable.Id_doodle_btn_hide_panel) {
           // mSettingsPanel.removeCallbacks(mHideDelayRunnable);
           // mSettingsPanel.removeCallbacks(mShowDelayRunnable);
            v.setSelected(!v.isSelected());
            if (!mBtnHidePanel.isSelected()) {
                showView(mSettingsPanel);
            } else {
                hideView(mSettingsPanel);
            }
        } else if (v.getId() == ResourceTable.Id_doodle_btn_finish) {
            mDoodle.save();
        } else if (v.getId() == ResourceTable.Id_doodle_btn_back) {
            if (mDoodle.getAllItem() == null || mDoodle.getItemCount() == 0) {
                terminateAbility();
                return;
            }
            if (!(DoodleParams.getDialogInterceptor() != null
                    && DoodleParams.getDialogInterceptor().onShow(DoodleActivity.this, mDoodle, DoodleParams.DialogType.SAVE))) {
               //todo 撤回操作

               /* DialogController.showMsgDialog(DoodleActivity.this, getString(R.string.doodle_saving_picture), null, getString(R.string.doodle_cancel),
                        getString(R.string.doodle_save), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDoodle.save();
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finish();
                            }
                        });*/
            }
        } else if (v.getId() == ResourceTable.Id_doodle_btn_rotate) {
            // 旋转图片
            if (mRotateAnimator == null) {
                mRotateAnimator = new AnimatorProperty();
                mRotateAnimator.setStateChangedListener(new Animator.StateChangedListener() {
                    @Override
                    public void onStart(Animator animator) {

                    }

                    @Override
                    public void onStop(Animator animator) {

                    }

                    @Override
                    public void onCancel(Animator animator) {

                    }

                    @Override
                    public void onEnd(Animator animator) {
                        mDoodle.setDoodleRotation(mDoodle.getDoodleRotation() + 90);
                    }

                    @Override
                    public void onPause(Animator animator) {

                    }

                    @Override
                    public void onResume(Animator animator) {

                    }
                });
                mRotateAnimator.setDuration(250);
            }
            if (mRotateAnimator.isRunning()) {
                return;
            }

            mRotateAnimator.rotate(90);
            mRotateAnimator.start();
        } else if (v.getId() == ResourceTable.Id_doodle_selectable_edit) {
            if (mTouchGestureListener.getSelectedItem() instanceof DoodleText) {
                createDoodleText((DoodleText) mTouchGestureListener.getSelectedItem(), -1, -1);
            } else if (mTouchGestureListener.getSelectedItem() instanceof DoodleBitmap) {
                createDoodleBitmap((DoodleBitmap) mTouchGestureListener.getSelectedItem(), -1, -1);
            }
        } else if (v.getId() == ResourceTable.Id_doodle_selectable_remove) {
            mDoodle.removeItem(mTouchGestureListener.getSelectedItem());
            mTouchGestureListener.setSelectedItem(null);
        } else if (v.getId() == ResourceTable.Id_doodle_selectable_top) {
            mDoodle.topItem(mTouchGestureListener.getSelectedItem());
        } else if (v.getId() == ResourceTable.Id_doodle_selectable_bottom) {
            mDoodle.bottomItem(mTouchGestureListener.getSelectedItem());
        } else if (v.getId() == ResourceTable.Id_btn_hand_write) {
            mDoodle.setShape(DoodleShape.HAND_WRITE);
        } else if (v.getId() == ResourceTable.Id_btn_arrow) {
            mDoodle.setShape(DoodleShape.ARROW);
        } else if (v.getId() == ResourceTable.Id_btn_line) {
            mDoodle.setShape(DoodleShape.LINE);
        } else if (v.getId() == ResourceTable.Id_btn_holl_circle) {
            mDoodle.setShape(DoodleShape.HOLLOW_CIRCLE);
        } else if (v.getId() == ResourceTable.Id_btn_fill_circle) {
            mDoodle.setShape(DoodleShape.FILL_CIRCLE);
        } else if (v.getId() == ResourceTable.Id_btn_holl_rect) {
            mDoodle.setShape(DoodleShape.HOLLOW_RECT);
        } else if (v.getId() == ResourceTable.Id_btn_fill_rect) {
            mDoodle.setShape(DoodleShape.FILL_RECT);
        } else if (v.getId() == ResourceTable.Id_btn_mosaic_level1) {
            if (v.isSelected()) {
                return;
            }

            mMosaicLevel = DoodlePath.MOSAIC_LEVEL_1;
            mDoodle.setColor(DoodlePath.getMosaicColor(mDoodle, mMosaicLevel));
            v.setSelected(true);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level2).setSelected(false);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level3).setSelected(false);
            if (mTouchGestureListener.getSelectedItem() != null) {
                mTouchGestureListener.getSelectedItem().setColor(mDoodle.getColor().copy());
            }
        } else if (v.getId() == ResourceTable.Id_btn_mosaic_level2) {
            if (v.isSelected()) {
                return;
            }

            mMosaicLevel = DoodlePath.MOSAIC_LEVEL_2;
            mDoodle.setColor(DoodlePath.getMosaicColor(mDoodle, mMosaicLevel));
            v.setSelected(true);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level1).setSelected(false);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level3).setSelected(false);
            if (mTouchGestureListener.getSelectedItem() != null) {
                mTouchGestureListener.getSelectedItem().setColor(mDoodle.getColor().copy());
            }
        } else if (v.getId() == ResourceTable.Id_btn_mosaic_level3) {
            if (v.isSelected()) {
                return;
            }

            mMosaicLevel = DoodlePath.MOSAIC_LEVEL_3;
            mDoodle.setColor(DoodlePath.getMosaicColor(mDoodle, mMosaicLevel));
            v.setSelected(true);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level1).setSelected(false);
            mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level2).setSelected(false);
            if (mTouchGestureListener.getSelectedItem() != null) {
                mTouchGestureListener.getSelectedItem().setColor(mDoodle.getColor().copy());
            }
        } else if (v.getId() == ResourceTable.Id_btn_redo) {
            if (!mDoodle.redo(1)) {
                mRedoBtn.setVisibility(Component.HIDE);
            }
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEY_BACK) {
            if (mDoodleView.isEditMode()) {
                mDoodleView.setEditMode(false);
                return true;
            }else{
                terminateAbility();

            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() { // 返回键监听
        findComponentById(ResourceTable.Id_doodle_btn_back).simulateClick();
    }

    private void showView(Component view) {
        if (view.getVisibility() == Component.VISIBLE) {
            return;
        }
        AnimatorProperty animatorProperty = new AnimatorProperty(view);
        animatorProperty.alpha(1);
        animatorProperty.alphaFrom(0);
        view.setVisibility(Component.VISIBLE);
        animatorProperty.start();
        
    }

    private void hideView(Component view) {
        if (view.getVisibility() != Component.VISIBLE) {
            return;
        }
        AnimatorProperty animatorProperty = new AnimatorProperty(view);
        animatorProperty.alpha(0);
        animatorProperty.alphaFrom(1);
        animatorProperty.start();
        view.setVisibility(Component.HIDE);
        
    }

  /*  *
     * 包裹DoodleView，监听相应的设置接口，以改变UI状态*/

    private class DoodleViewWrapper extends DoodleView {

        public DoodleViewWrapper(Context context, PixelMap bitmap, boolean optimizeDrawing, IDoodleListener listener) {
            super(context, bitmap, optimizeDrawing, listener);
        }

        private Map<IDoodlePen, Integer> mBtnPenIds = new HashMap<>();

        {
            mBtnPenIds.put(DoodlePen.BRUSH, ResourceTable.Id_btn_pen_hand);
            mBtnPenIds.put(DoodlePen.MOSAIC, ResourceTable.Id_btn_pen_mosaic);
            mBtnPenIds.put(DoodlePen.COPY, ResourceTable.Id_btn_pen_copy);
            mBtnPenIds.put(DoodlePen.ERASER, ResourceTable.Id_btn_pen_eraser);
            mBtnPenIds.put(DoodlePen.TEXT, ResourceTable.Id_btn_pen_text);
            mBtnPenIds.put(DoodlePen.BITMAP, ResourceTable.Id_btn_pen_bitmap);
        }

        @Override
        public void setPen(IDoodlePen pen) {
            IDoodlePen oldPen = getPen();
            super.setPen(pen);

            mMosaicMenu.setVisibility(HIDE);
            mEditBtn.setVisibility(HIDE); // edit btn
            if (pen == DoodlePen.BITMAP || pen == DoodlePen.TEXT) {
                mEditBtn.setVisibility(Component.VISIBLE); // edit btn
                mShapeContainer.setVisibility(HIDE);
                if (pen == DoodlePen.BITMAP) {
                    mColorContainer.setVisibility(HIDE);
                } else {
                    mColorContainer.setVisibility(VISIBLE);
                }
            } else if (pen == DoodlePen.MOSAIC) {
                mMosaicMenu.setVisibility(VISIBLE);
                mShapeContainer.setVisibility(VISIBLE);
                mColorContainer.setVisibility(HIDE);
            } else {
                mShapeContainer.setVisibility(VISIBLE);
                if (pen == DoodlePen.COPY || pen == DoodlePen.ERASER) {
                    mColorContainer.setVisibility(HIDE);
                } else {
                    mColorContainer.setVisibility(VISIBLE);
                }
            }
            setSingleSelected(mBtnPenIds.values(), mBtnPenIds.get(pen));

            if (mTouchGestureListener.getSelectedItem() == null) {
                mPenSizeMap.put(oldPen, getSize()); // save
                Float size = mPenSizeMap.get(pen); // restore
                if (size != null) {
                    mDoodle.setSize(size);
                }
                if (isEditMode()) {
                    mShapeContainer.setVisibility(HIDE);
                    mColorContainer.setVisibility(HIDE);
                    mMosaicMenu.setVisibility(HIDE);
                }
            } else {
                mShapeContainer.setVisibility(HIDE);
                return;
            }

            if (pen == DoodlePen.BRUSH) {

                Element colorBg = mBtnColor.getBackgroundElement();
                if (colorBg instanceof PixelMapElement) {
                    mDoodle.setColor(new DoodleColor(((PixelMapElement) colorBg).getPixelMap()));
                } else {
                    mDoodle.setColor(new DoodleColor(getColor(ResourceTable.Id_btn_set_color)));
                }



            } else if (pen == DoodlePen.MOSAIC) {
                if (mMosaicLevel <= 0) {
                    mMosaicMenu.findComponentById(ResourceTable.Id_btn_mosaic_level2).simulateClick();
                } else {
                    mDoodle.setColor(DoodlePath.getMosaicColor(mDoodle, mMosaicLevel));
                }
            } else if (pen == DoodlePen.COPY) {

            } else if (pen == DoodlePen.ERASER) {

            } else if (pen == DoodlePen.TEXT) {

                Element colorBg = mBtnColor.getBackgroundElement();
                if (colorBg instanceof PixelMapElement) {
                    mDoodle.setColor(new DoodleColor(((PixelMapElement) colorBg).getPixelMap()));
                } else {

                    mDoodle.setColor(new DoodleColor(getColor(ResourceTable.Id_btn_set_color)));
                }
            } else if (pen == DoodlePen.BITMAP) {
                Element colorBg = mBtnColor.getBackgroundElement();
                if (colorBg instanceof PixelMapElement) {
                    mDoodle.setColor(new DoodleColor(((PixelMapElement) colorBg).getPixelMap()));

                } else {
                    if (mBtnColor != null){
                        float[] cl = mBtnColor.getBackgroundElement().getColorMatrix().getMatrix();
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append("#");
                        for (int i = 0; i < cl.length; i++)
                            stringBuilder.append(cl[i]);
                        mDoodle.setColor(new DoodleColor(getColor(ResourceTable.Id_btn_set_color)));
                    }

                }
            }
        }

        public  int getColor( int resId) {
            try {
                return getResourceManager().getElement(resId).getColor();
//            return context.getColor(resId);//在tv上报错java.lang.NoSuchMethodError: No interface method getColor(I)
            } catch (Exception ignore) {
            }
            return 0;
        }

        private Map<IDoodleShape, Integer> mBtnShapeIds = new HashMap<>();

        {
            mBtnShapeIds.put(DoodleShape.HAND_WRITE, ResourceTable.Id_btn_hand_write);
            mBtnShapeIds.put(DoodleShape.ARROW, ResourceTable.Id_btn_arrow);
            mBtnShapeIds.put(DoodleShape.LINE, ResourceTable.Id_btn_line);
            mBtnShapeIds.put(DoodleShape.HOLLOW_CIRCLE, ResourceTable.Id_btn_holl_circle);
            mBtnShapeIds.put(DoodleShape.FILL_CIRCLE, ResourceTable.Id_btn_fill_circle);
            mBtnShapeIds.put(DoodleShape.HOLLOW_RECT, ResourceTable.Id_btn_holl_rect);
            mBtnShapeIds.put(DoodleShape.FILL_RECT, ResourceTable.Id_btn_fill_rect);

        }

        @Override
        public void setShape(IDoodleShape shape) {
            super.setShape(shape);
            setSingleSelected(mBtnShapeIds.values(), mBtnShapeIds.get(shape));
        }

        Text mPaintSizeView = (Text) DoodleActivity.this.findComponentById(ResourceTable.Id_paint_size_text);

        @Override
        public void setSize(float paintSize) {
            super.setSize(paintSize);
        /*    if ( paintSize <= 0)
                mEditSizeSeekBar.setProgressValue(1);
            else
                mEditSizeSeekBar.setProgressValue((int) paintSize);*/
            mPaintSizeView.setText("" + (int) paintSize);

            if (mTouchGestureListener != null && mTouchGestureListener.getSelectedItem() != null) {
                mTouchGestureListener.getSelectedItem().setSize(getSize());
            }
        }

        @Override
        public void setColor(IDoodleColor color) {
            IDoodlePen pen = getPen();
            super.setColor(color);

            DoodleColor doodleColor = null;
            if (color instanceof DoodleColor) {
                doodleColor = (DoodleColor) color;
            }
            if (doodleColor != null
                    && canChangeColor(pen)) {
                if (doodleColor.getType() == DoodleColor.Type.COLOR) {
                    ShapeElement backgroundElement = new ShapeElement();
                    backgroundElement.setShape(ShapeElement.RECTANGLE);
                    backgroundElement.setRgbColor(RgbColor.fromArgbInt(doodleColor.getColor()));
                    mBtnColor.setBackground(backgroundElement);
                } else if (doodleColor.getType() == DoodleColor.Type.BITMAP) {
                    mBtnColor.setBackground(new PixelMapElement(doodleColor.getBitmap()));
                }

                if (mTouchGestureListener.getSelectedItem() != null) {
                    mTouchGestureListener.getSelectedItem().setColor(getColor().copy());
                }
            }

            if (doodleColor != null && pen == DoodlePen.MOSAIC
                    && doodleColor.getLevel() != mMosaicLevel) {
                switch (doodleColor.getLevel()) {
                    case DoodlePath.MOSAIC_LEVEL_1:
                        DoodleActivity.this.findComponentById(ResourceTable.Id_btn_mosaic_level1).simulateClick();
                        break;
                    case DoodlePath.MOSAIC_LEVEL_2:
                        DoodleActivity.this.findComponentById(ResourceTable.Id_btn_mosaic_level2).simulateClick();
                        break;
                    case DoodlePath.MOSAIC_LEVEL_3:
                        DoodleActivity.this.findComponentById(ResourceTable.Id_btn_mosaic_level3).simulateClick();
                        break;
                }
            }
        }

        @Override
        public void enableZoomer(boolean enable) {
            super.enableZoomer(enable);
            DoodleActivity.this.findComponentById(ResourceTable.Id_btn_zoomer).setSelected(enable);
            if (enable) {
                //Toast.makeText(DoodleActivity.this, "x" + mDoodleParams.mZoomerScale, Toast.LENGTH_SHORT).show();
                Toast.show("x" + mDoodleParams.mZoomerScale);
            }
        }

        @Override
        public boolean undo() {
            mTouchGestureListener.setSelectedItem(null);
            boolean res = super.undo();
            if (getRedoItemCount() > 0) {
                mRedoBtn.setVisibility(VISIBLE);
            } else {
                mRedoBtn.setVisibility(HIDE);
            }
            return res;
        }

        @Override
        public void clear() {
            super.clear();
            mTouchGestureListener.setSelectedItem(null);
            mRedoBtn.setVisibility(HIDE);
        }

        @Override
        public void addItem(IDoodleItem item) {
            super.addItem(item);
            if (getRedoItemCount() > 0) {
                mRedoBtn.setVisibility(VISIBLE);
            } else {
                mRedoBtn.setVisibility(HIDE);
            }
        }

        Component mBtnEditMode = DoodleActivity.this.findComponentById(ResourceTable.Id_doodle_btn_brush_edit);
        Boolean mLastIsDrawableOutside = null;

        @Override
        public void setEditMode(boolean editMode) {
            if (editMode == isEditMode()) {
                return;
            }

            super.setEditMode(editMode);
            mBtnEditMode.setSelected(editMode);
            if (editMode) {
                Toast.show( ResourceTable.String_doodle_edit_mode);
                mLastIsDrawableOutside = mDoodle.isDrawableOutside(); // save
                mDoodle.setIsDrawableOutside(true);
                mPenContainer.setVisibility(HIDE);
                mShapeContainer.setVisibility(HIDE);
                mSizeContainer.setVisibility(HIDE);
                mColorContainer.setVisibility(HIDE);
                mBtnUndo.setVisibility(HIDE);
                mMosaicMenu.setVisibility(HIDE);
            } else {
                if (mLastIsDrawableOutside != null) { // restore
                    mDoodle.setIsDrawableOutside(mLastIsDrawableOutside);
                }
                mTouchGestureListener.center(); // center picture
                if (mTouchGestureListener.getSelectedItem() == null) { // restore
                    setPen(getPen());
                }
                mTouchGestureListener.setSelectedItem(null);
                mPenContainer.setVisibility(VISIBLE);
                mSizeContainer.setVisibility(VISIBLE);
                mBtnUndo.setVisibility(VISIBLE);
            }
        }

        private void setSingleSelected(Collection<Integer> ids, int selectedId) {
            for (int id : ids) {
                if (id == selectedId) {
                    DoodleActivity.this.findComponentById(id).setSelected(true);
                } else {
                    DoodleActivity.this.findComponentById(id).setSelected(false);
                }
            }
        }
    }

}
